package com.babel.util.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@SuppressWarnings({"rawtypes","unchecked"})
@Service
public class RedisManage {

	@Autowired
    private RedisTemplate redisTemplate;
	
	public Object get(String key){
    	return redisTemplate.opsForValue().get(key);
    }
	
	public void set(String key,Object value){
		redisTemplate.opsForValue().set(key, value);
    }
	
	public void set(String key,Object value,long timeout){
		redisTemplate.opsForValue().set(key, value);
		redisTemplate.expire(key, timeout, TimeUnit.MILLISECONDS);
	}
	
    public void delete(String key){
    	redisTemplate.delete(key);
    }
    
    public boolean setNX(String key,long timeout,Object value){
    	boolean retVal= redisTemplate.opsForValue().setIfAbsent(key, value);
    	if(retVal){
    		redisTemplate.expire(key, timeout, TimeUnit.MILLISECONDS);
    	}
    	return retVal;
    }
    
    public void setbit(String key,long offset,boolean value){
    	redisTemplate.opsForValue().setBit(key, offset, value);
    }
    
    public Boolean getbit(String key,long offset){
    	return redisTemplate.opsForValue().getBit(key, offset);
    }
    
    public Long getbitcount(String key){
    	return redisTemplate.getConnectionFactory().getConnection().bitCount(key.getBytes());
    }
    
    public Long getbitcount(String key,long begin,long end){
    	return redisTemplate.getConnectionFactory().getConnection().bitCount(key.getBytes(),begin,end);
    }
}
